package cn.kgc.springboot.service.impl;

import cn.kgc.springboot.dto.RolePageDTO;
import cn.kgc.springboot.entity.RolePers;
import cn.kgc.springboot.entity.UserRole;
import cn.kgc.springboot.mapper.RolePersMapper;
import cn.kgc.springboot.mapper.UserRoleMapper;
import cn.kgc.springboot.util.CodeMsg;
import cn.kgc.springboot.util.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.springboot.entity.Role;
import cn.kgc.springboot.service.RoleService;
import cn.kgc.springboot.mapper.RoleMapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired(required = false)
    private UserRoleMapper userRoleMapper;

    @Autowired(required = false)
    private RolePersMapper rolePersMapper;

    //2.分页
    @Override
    public ResponseResult selectPage(RolePageDTO rolePageDTO) {
        //接收从前端传来的数据:page limit
        Integer page = rolePageDTO.getPage();
        Integer limit = rolePageDTO.getLimit();
        String roleName = rolePageDTO.getRoleName();

        Page<Role> rolePage = new Page<>(page, limit);

        //构建查询条件 搜索
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.like(!StringUtils.isEmptyOrWhitespaceOnly(roleName), Role::getRoleName,roleName);
        roleMapper.selectPage(rolePage,lambda);

        //封装返回数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());
        responseResult.setData(rolePage.getRecords());  //所有分页的记录
        responseResult.setCount(rolePage.getTotal());   //总条数

        return responseResult;
    }

    //5.删除操作
    @Override
    public ResponseResult deleteByIds(String ids) {
        ResponseResult responseResult = new ResponseResult();
        //将ids的字符串转换为 集合类型
        String[] strIds = ids.split(",");
        ArrayList<Integer> intIds = new ArrayList<>();
        for (String strId : strIds) {
            intIds.add(Integer.valueOf(strId));
        }

        //判定用户角色关联表(user_role)中是否有当前角色，有就不能删除，没有就可以删除
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("role_id", intIds);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        //用户角色关联表中，没有当前角色，即选中后个数为0，若是存在当前角色，则选中个数大于0
        //(1)用户角色关联表(user_role)存在当前角色
        if(userRoles.size()>0){
            //提示角色被占用
            responseResult.setMsg(CodeMsg.ROLE_USED.getMsg());
            responseResult.setCode(CodeMsg.ROLE_USED.getCode());

            //(2)用户角色关联表(user_role)不存在当前角色，可以删除
        }else{
            //删除角色信息（删除role中的角色信息）
            roleMapper.deleteBatchIds(intIds);
            //删除角色权限关联表(role_pers)中的信息
            QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
            rolePersQueryWrapper.in("role_id", intIds);
            rolePersMapper.delete(rolePersQueryWrapper);

            responseResult.setMsg(CodeMsg.DELETE_SUCCESS.getMsg());
            responseResult.setCode(CodeMsg.DELETE_SUCCESS.getCode());

        }
        return responseResult;
    }

    //6.回显: selectPermissionByRoleId,根据角色id(role_id)，查询权限id(per_id)，用于权限数据默认选中
    @Override
    public ResponseResult selectPermissionByRoleId(Integer roleId) {

        QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
        rolePersQueryWrapper.eq("role_id", roleId);
        List<RolePers> rolePers = rolePersMapper.selectList(rolePersQueryWrapper);
        System.out.println("rolePers = " + rolePers);
        //获取权限id(per_id)
        ArrayList<Integer> perIds = new ArrayList<>();
        rolePers.forEach(rp->{
            perIds.add(rp.getPerId());
        });

        //封装返回数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(perIds);
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());

        return responseResult;
    }

    //7.添加权限,为用户添加新的权限(per_id)
    @Override
    public ResponseResult addRolePermission(Integer roleId, String permissionIds) {

        //(1)首先删除roleId对应的权限(根据该用户id，删除role_pers表中对应role_id的数据)
        QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
        rolePersQueryWrapper.eq("role_id", roleId);
        rolePersMapper.delete(rolePersQueryWrapper);

        //(2)添加roleId,即添加对应的最新的权限
        String[] strPermisission = permissionIds.split(","); //将获取的perId数据，用逗号分割，并进行遍历
        //遍历，获取perId，并将其获取到的roleId和perId添加到role_pers表中
        for (String perId : strPermisission) {
            RolePers rolePers = new RolePers();
            rolePers.setPerId(Integer.valueOf(perId));
            rolePers.setRoleId(roleId);
            rolePersMapper.insert(rolePers);

            /*备注：
             * Integer.valueOf()可以将基本类型int转换为包装类型Integer，
             * 或者将String转换成Integer，String如果为Null或“”都会报错
             * */
        }

        ResponseResult responseResult = new ResponseResult();
        responseResult.setMsg(CodeMsg.ADD_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.ADD_SUCCESS.getCode());

        return responseResult;
    }
}




